package com.orhon.smartcampus.modules.base.mutation;

import com.alibaba.fastjson.JSON;
import com.orhon.smartcampus.basicComponents.Result;
import com.orhon.smartcampus.modules.base.dao.RegionsDao;
import com.orhon.smartcampus.modules.base.entity.Regions;
import com.orhon.smartcampus.modules.base.gqlInputModel.GQLRegionInput;
import com.orhon.smartcampus.modules.base.inputMapper.RegionInputMapper;
import graphql.schema.DataFetcher;
import graphql.schema.DataFetchingEnvironment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class AddRegionMutation implements DataFetcher {


    @Autowired
    RegionsDao regionsDao;

    /**
     * 新增/修改地区信息
     * editor : ths
     */
    @Override
    public Object get(DataFetchingEnvironment environment) throws Exception {

        GQLRegionInput input = RegionInputMapper.MAPPER.mapInput(environment.getArgument("inputData"));

        Regions regions = null;

        if (input.getId() != null) {
            regions = regionsDao.get(Regions.class, input.getId());
            regions.setUpdatedAt(new Date());
        } else {
            regions = new Regions();
            regions.setCreatedAt(new Date());
        }
        if(input.getName() != null){

            regions.setRegionName(JSON.toJSONString(input.getName()));
        }
        if(input.getSlug() != null){

            regions.setRegionSlug(input.getSlug());
        }
        if(input.getName() != null){

            regions.setRegionName(JSON.toJSONString(input.getName()));
        }
        if (input.getParent() != null) {
            Regions parent = regionsDao.get(Regions.class, Long.valueOf(input.getParent()));
            regions.setParentRegions(parent);
        }
        if(input.getLevel() != null){

            regions.setLevel(input.getLevel());
        }
        if(input.getOrder() != null){

            regions.setRegionOrder(input.getOrder());
        }
        try {
            regionsDao.saveOrUpdate(regions);
        } catch (Exception e) {
            return Result.error(500, "" + e);
        }
        return Result.ok();
    }
}

